import Vue from "vue";
import Router from "vue-router";
import getRoutes from './routes'
import { Message } from 'element-ui'

Vue.use(Router);

// 固定路由
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue'),
    meta: {
      title: '登录',
      parentTitle: ''
    }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404/index.vue'),
    meta: {
      title: '404',
      parentTitle: ''
    }
  }
]

const createRouter = () => new Router({
  linkActiveClass: 'active',
  mode: 'history',
  base: '/admin',
  routes
})
const router = createRouter()

//防止刷新当前页面时动态路由还没挂在vue上出现空白页面，在挂载之前router.addRoutes(routerlist)
if (localStorage.getItem('routes')) {
  if (JSON.parse(localStorage.getItem('routes')).length === 0) {
    localStorage.removeItem('token')
    Message.error('你没有可访问的页面权限，请更换账号重新登录')
    router.push({
      path: '/login'
    })
  } else {
    //这里是调用router.js里的方法拿到动态路由
    getRoutes(JSON.parse(localStorage.getItem('routes')), routes => {
      router.matcher = createRouter().matcher
      router.addRoutes(routes)
    })
  }
}


// 设置html标题
function setTitle(to) {
  document.title = `${to.meta.parentTitle || '标书管理系统'} - ${to.meta.title}`
}

router.beforeEach((to, from, next) => {
  setTitle(to)
  if (localStorage.getItem('token')) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      console.log(to)
      // login.wsConnect(window.localStorage.getItem('userId'))
      // 如果页面有对应组件则显示，没有对应的组件则跳转到404页面
      if (to.meta.isComponent) {
        next()
      } else {
        to.path === '/404' ? next() : next('/404')
      }
    }
  } else {
    to.path === '/login' ? next() : next({ path: '/login' })
  }
})

export default router
